package fi.solita.dojo.mazeserver.client

import java.net._

import java.io._
import java.util.concurrent._

import scala.actors._
import scala.actors.Actor._
import fi.solita.dojo.mazeserver.game._

abstract sealed class ServerMessage
case class Connect(socket:  Socket) extends ServerMessage
case class Write(client: String, message:  String) extends ServerMessage
case class Remove(client: String) extends ServerMessage
case class Init(client: String, socket: Socket) extends ServerMessage

object ClientService extends Actor {

	private val clients = new ConcurrentHashMap[String, Socket](); // need not be concurrent
 
	def act() {
		loop {
			receive {
			case Connect(socket: Socket) => {
				val t = new Thread(new ClientThread(socket))
				t.start
				println("started client thread for socket " + socket)
			}

			case Write(client:  String, message:  String) => {
				val out = clients.get(client)
				try {
					write(new OutputStreamWriter(out.getOutputStream(), "ISO-8859-1"), message)
				} catch {
				  case ex: Exception => {} // socket was closed or client had quit
				}
			}

			case Remove(client: String) => {
                clients.remove(client)
			}
   
			case Init(client: String, socket: Socket) => {
                clients.put(client, socket)
			}
   
			}
		}
	}

	def clientNameInUse(name: String): Boolean = clients.keySet.contains(name)
 
	def write(out:  Writer, line: String) {
		out.write(line + "\n")
		out.flush()
	}
}


